<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/vhuichen.ico">
  <link rel="mask-icon" href="/vhuichen.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"vhuichen.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.13.0","exturl":false,"sidebar":{"position":"left","display":"display","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="前言自苹果禁用热更新以来（实际上就是禁用了 dlsym 等几个接口），使用了 JSpatch 等热更新库的应用也就无法更新了；那么有没有一种方式可以代替通过 dlsym 实现的热更新呢？ OCRunner &amp; MangoFix这两个库都可以实现 iOS 的热更新，使用的原理是相同的，都是通过语法分析、词法分析最终生成抽象语法树，再通过解析器解析，这里相当于自己写了一个编译器；而底层方法交换">
<meta property="og:type" content="article">
<meta property="og:title" content="libffi 探究">
<meta property="og:url" content="https://vhuichen.github.io/2022/04/iOS/libffi%E6%8E%A2%E7%A9%B6%20/index.html">
<meta property="og:site_name" content="vhuichen">
<meta property="og:description" content="前言自苹果禁用热更新以来（实际上就是禁用了 dlsym 等几个接口），使用了 JSpatch 等热更新库的应用也就无法更新了；那么有没有一种方式可以代替通过 dlsym 实现的热更新呢？ OCRunner &amp; MangoFix这两个库都可以实现 iOS 的热更新，使用的原理是相同的，都是通过语法分析、词法分析最终生成抽象语法树，再通过解析器解析，这里相当于自己写了一个编译器；而底层方法交换">
<meta property="og:locale">
<meta property="article:published_time" content="2022-04-19T16:00:00.000Z">
<meta property="article:modified_time" content="2021-04-21T16:00:00.000Z">
<meta property="article:author" content="vhuichen">
<meta property="article:tag" content="libffi">
<meta property="article:tag" content="热更新">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://vhuichen.github.io/2022/04/iOS/libffi%E6%8E%A2%E7%A9%B6%20/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-Hans","comments":true,"permalink":"https://vhuichen.github.io/2022/04/iOS/libffi%E6%8E%A2%E7%A9%B6%20/","path":"2022/04/iOS/libffi探究 /","title":"libffi 探究"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>libffi 探究 | vhuichen</title>
  






  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">vhuichen</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录、分享</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section">Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section">About</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#OCRunner-amp-MangoFix"><span class="nav-number">1.1.</span> <span class="nav-text">OCRunner &amp; MangoFix</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#libffi"><span class="nav-number">2.</span> <span class="nav-text">libffi</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%B0%83%E7%94%A8%E6%83%AF%E4%BE%8B-Calling-Convention"><span class="nav-number">3.</span> <span class="nav-text">调用惯例(Calling Convention)</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#libffi-%E8%B0%83%E7%94%A8%E4%BB%BB%E6%84%8F-OC-%E6%96%B9%E6%B3%95"><span class="nav-number"></span> <span class="nav-text">libffi 调用任意 OC 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E9%97%AD%E5%8C%85%E5%B9%B6%E4%BA%A4%E6%8D%A2-IMP"><span class="nav-number">1.</span> <span class="nav-text">创建闭包并交换 IMP</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%B0%86%E9%97%AD%E5%8C%85%E5%9B%9E%E8%B0%83%E8%BD%AC%E5%8F%91%E5%88%B0%E6%96%B0%E7%9A%84IMP%E4%B8%8A"><span class="nav-number">2.</span> <span class="nav-text">将闭包回调转发到新的IMP上</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%93%E5%AD%98"><span class="nav-number">3.</span> <span class="nav-text">缓存</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%81%97%E7%95%99%E9%97%AE%E9%A2%98"><span class="nav-number">4.</span> <span class="nav-text">遗留问题</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Demo"><span class="nav-number">5.</span> <span class="nav-text">Demo</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="vhuichen"
      src="/images/vhuichen.jpg">
  <p class="site-author-name" itemprop="name">vhuichen</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2022/04/iOS/libffi%E6%8E%A2%E7%A9%B6%20/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="libffi 探究 | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          libffi 探究
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2022-04-20 00:00:00" itemprop="dateCreated datePublished" datetime="2022-04-20T00:00:00+08:00">2022-04-20</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2021-04-22 00:00:00" itemprop="dateModified" datetime="2021-04-22T00:00:00+08:00">2021-04-22</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h4 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h4><p>自苹果禁用热更新以来（实际上就是禁用了 <code>dlsym</code> 等几个接口），使用了 JSpatch 等热更新库的应用也就无法更新了；<br>那么有没有一种方式可以代替通过 <code>dlsym</code> 实现的热更新呢？</p>
<h5 id="OCRunner-amp-MangoFix"><a href="#OCRunner-amp-MangoFix" class="headerlink" title="OCRunner &amp; MangoFix"></a>OCRunner &amp; MangoFix</h5><p>这两个库都可以实现 iOS 的热更新，使用的原理是相同的，都是通过语法分析、词法分析最终生成抽象语法树，再通过解析器解析，这里相当于自己写了一个编译器；而底层方法交换是通过 libffi  + runtime 实现的，这篇文章就来简单了解下 libffi 这个库的使用。</p>
<h4 id="libffi"><a href="#libffi" class="headerlink" title="libffi"></a>libffi</h4><p><code>FFI</code> 的全名是 Foreign Function Interface (外部函数接口)<br>libffi 提供了一套底层接口，在知道函数签名的情况下，可以根据相关接口完成函数调用；</p>
<h4 id="调用惯例-Calling-Convention"><a href="#调用惯例-Calling-Convention" class="headerlink" title="调用惯例(Calling Convention)"></a>调用惯例(Calling Convention)</h4><p>函数调用是通过堆栈体现出来的，在调用函数时，需要按照约定将相关的参数入栈，<br>而这种约定就叫做：调用惯例(Calling Convention)<br>也就是说只要我们按照这个约定存放函数调用时使用的参数，就可实现函数调用的效果；<br>libffi 也就是实现了这样的一个功能。</p>
<h3 id="libffi-调用任意-OC-方法"><a href="#libffi-调用任意-OC-方法" class="headerlink" title="libffi 调用任意 OC 方法"></a>libffi 调用任意 OC 方法</h3><p>实现步骤：  </p>
<ol>
<li>通过 libffi 创建 closure 闭包  </li>
<li>交换函数指针；之后调用原始方法，因为 imp 已经修改，最终会调用到闭包中  </li>
<li>在闭包回调函数里面，将 imp 替换成新的，将消息通过 ffi_call 发送出去</li>
</ol>
<p><strong>换句话说通过 libffi 的闭包功能，再加上 OC 提供给我们的 runtime ，一样也可以实现任意方法的 hook 功能；同时也为热修复提供了基础能力。</strong></p>
<span id="more"></span>

<h4 id="创建闭包并交换-IMP"><a href="#创建闭包并交换-IMP" class="headerlink" title="创建闭包并交换 IMP"></a>创建闭包并交换 IMP</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">- (void)closureInit &#123;</span><br><span class="line">    Method method = class_getInstanceMethod(sourceClass, sourceSelector);</span><br><span class="line">    const char *types = method_getTypeEncoding(method);</span><br><span class="line">    NSMethodSignature *sign = [NSMethodSignature signatureWithObjCTypes:types];</span><br><span class="line">    unsigned int nargs = (unsigned int)sign.numberOfArguments;</span><br><span class="line">    </span><br><span class="line">    argumentTypes = malloc(sizeof(ffi_type *) * nargs);</span><br><span class="line">    argumentTypes[0] = &amp;ffi_type_pointer;</span><br><span class="line">    argumentTypes[1] = &amp;ffi_type_pointer;</span><br><span class="line">    for (int i = 2; i &lt; nargs; i++) &#123;</span><br><span class="line">        argumentTypes[i] = [sign ffi_getArgumentTypeAtIndex:i];</span><br><span class="line">    &#125;</span><br><span class="line">    ffi_type *ffiReturnType = [sign ffi_methodReturnType];</span><br><span class="line">    // 初始化函数模板</span><br><span class="line">    ffi_prep_cif(&amp;cif, FFI_DEFAULT_ABI, nargs, ffiReturnType, argumentTypes);</span><br><span class="line">    // 创建 closure 对象</span><br><span class="line">    closure = ffi_closure_alloc(sizeof(ffi_closure), (void *)&amp;newIMP);</span><br><span class="line">    // 绑定 closure 对象</span><br><span class="line">    ffi_prep_closure_loc(closure, &amp;cif, callbackImp, (__bridge void *)self, NULL);</span><br><span class="line">    </span><br><span class="line">    method_setImplementation(method, newIMP);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li>ffi_type 表示参数类型</li>
<li>ffi_prep_cif 负责初始化函数模板（相当于函数签名）</li>
<li>ffi_closure_alloc 分配空间</li>
<li>ffi_prep_closure_loc 绑定闭包数据</li>
</ol>
<h4 id="将闭包回调转发到新的IMP上"><a href="#将闭包回调转发到新的IMP上" class="headerlink" title="将闭包回调转发到新的IMP上"></a>将闭包回调转发到新的IMP上</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">void ffiClosureCalled(ffi_cif *cif, void *ret, void **args, void *userdata) &#123;</span><br><span class="line">    VCHFFIClosure *closure = (__bridge VCHFFIClosure *)userdata;</span><br><span class="line">    //更换新的imp </span><br><span class="line">    IMP imp = class_getMethodImplementation(closure-&gt;targetClass, closure-&gt;targetSelector);</span><br><span class="line">    </span><br><span class="line">    ffi_call(cif, imp, ret, args);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="缓存"><a href="#缓存" class="headerlink" title="缓存"></a>缓存</h4><p>ffi 生成的闭包数据必须缓存起来，这里写了个类单独处理闭包相关逻辑。<br>考虑到每个类可以 hook 多个方法，每个方法又必须对应一个闭包，所以缓存结构就是一个哈希表，key 表示 class，value 表示多个方法的集合，集合也是一个哈希表，key表示方法名，value表示对应的闭包；</p>
<h4 id="遗留问题"><a href="#遗留问题" class="headerlink" title="遗留问题"></a>遗留问题</h4><ol>
<li>闭包释放时要怎么销毁内存</li>
</ol>
<h4 id="Demo"><a href="#Demo" class="headerlink" title="Demo"></a>Demo</h4><p><a target="_blank" rel="noopener" href="https://github.com/vhuichen/VCHFFIHook.git">Demo</a></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/libffi/" rel="tag"># libffi</a>
              <a href="/tags/%E7%83%AD%E6%9B%B4%E6%96%B0/" rel="tag"># 热更新</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/03/iOS/iOS%E5%AF%B9%E8%B1%A1%E4%BB%80%E4%B9%88%E6%97%B6%E5%80%99%E5%8A%A0%E5%85%A5%E8%87%AA%E5%8A%A8%E9%87%8A%E6%94%BE%E6%B1%A0/" rel="prev" title="ARC下，对象什么时候加入自动释放池">
                  <i class="fa fa-chevron-left"></i> ARC下，对象什么时候加入自动释放池
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/05/NetworkProtocol/KCP/KCP/" rel="next" title="KCP 协议">
                  KCP 协议 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2015 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vhuichen</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
